package com.ttl.bc.ap.debitnote2.db;

import java.io.UnsupportedEncodingException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;

import com.ttl.bc.ap.ap.bean.BCAPBean;
import com.ttl.bc.ap.ap.db.BCAPDAO;


import com.ttl.bc.ap.debitnote2.action.BCDebitNote2Form;
import com.ttl.bc.ap.debitnote2.bean.BCDebitNote2;
import com.ttl.bc.ap.debitnote2.bean.BCDebitNoteSub2;
import com.ttl.bc.ap.debitnote2.bean.BCInvDebitNote2;
import com.ttl.bc.ap.invoice.bean.BCAPInvoiceBean;
import com.ttl.bc.ap.invoice.bean.BCAPInvoiceSubBean;
import com.ttl.bc.ap.invoice.bean.ITTL_P2;
import com.ttl.bc.ap.invoice.bo.BCAPInvoiceDAO;

import com.ttl.bc.ap.stkrefund.action.InvFindForm;
import com.ttl.bc.ap.stkrefund.db.BCStkRefundDAO;


import com.ttl.bc.master.itemunit.BCItemUnitBean;
import com.ttl.bc.processstock.bean.ProcessStockBean;
import com.ttl.bc.processstock.db.ProcessStockDAO;
import com.ttl.bc.vat.inputtax.bean.BCInputTaxBean;
import com.ttl.bc.vat.inputtax.db.BCInputTaxBO;
import com.ttl.bc.vat.inputtax.db.BCInputTaxDAO;
import com.ttl.common.util.CommonUtils;
import com.ttl.common.util.Page;

public class BCDebitNote2BO {

	@SuppressWarnings("unchecked")
	public Object findInv(ActionForm form, HttpServletRequest request) {

		InvFindForm invForm =(InvFindForm)form;
		String docNo = "";
		for(int i=0; i<invForm.getDocNoArray().length; i++) {
			docNo = docNo +"'"+ invForm.getDocNoArray()[i].trim() + "',";
		}
		if(docNo.length()>0) {
			docNo = docNo.substring(0, docNo.length()-1);
		}
		
		String hql = "FROM BCAPInvoiceBean " +
		 "WHERE  " +
		 " docNo in ( "+docNo+" )  ";		
		
		System.out.println(hql);
		
		BCAPInvoiceDAO dao = new BCAPInvoiceDAO();
		ArrayList results = (ArrayList)dao.find(hql);
		
		BCDebitNote2Form sf = new BCDebitNote2Form();
		if(results!=null && results.size()>0) {
			BCAPInvoiceBean i = (BCAPInvoiceBean)results.get(0);
						
			sf.setApCode(i.getApCode());
			sf.setDepartCode(i.getDepartCode());
			
			sf.setDocNoInv(i.getDocNo());
			sf.setOldAmount(i.getTotalAmount());
			
			Iterator it = i.getBcAPInvoiceSubs().iterator();
			while (it.hasNext()) {
				BCAPInvoiceSubBean isub = (BCAPInvoiceSubBean) it.next();
				sf.setItemCode(isub.getItemCode());
				sf.setItemName(isub.getItemName());
				sf.setDocNoInv2(i.getDocNo());
				sf.setPrice(isub.getPrice());
				sf.setBillQty(isub.getQty());
				sf.setWhCode(isub.getWhCode());
				sf.setShelfCode(isub.getShelfCode());
				sf.setUnitCode(isub.getUnitCode());
			}
			
			ArrayList apList = (ArrayList)(new BCAPDAO().find(i.getApCode()));
			if(apList!=null && apList.size()>0) {
				BCAPBean ap = (BCAPBean)apList.get(0);
				request.setAttribute("apCode", ap.getCode());
				request.setAttribute("apName", ap.getName1());
				
			}
		}
		
		return sf;//alSort;//alSort;//al;
	}	
	public void showFind(HttpServletRequest request) throws UnsupportedEncodingException {
//		String userName = (String)request.getSession().getAttribute("userName");			
		String monthFind = (String)request.getParameter("monthFind");
		String yearFind = (String)request.getParameter("yearFind");

//		String preDocNo  = (String)request.getSession().getAttribute("preDocNo")+"";
//		int userLevel =  (Integer)request.getSession().getAttribute("userLevel");		

		String	itemFind = "";
		if(request.getParameter("itemFind")!=null) {
			itemFind = ((String)request.getParameter("itemFind"));
			itemFind = new String(itemFind.getBytes("ISO8859_1"),"UTF-8");
			request.setAttribute("itemFind", itemFind.trim());
		}		
		
		if(monthFind==null) {			
			monthFind = CommonUtils.getCurrentDateFormat("MM");										
		}
		
		if(yearFind==null) {
			yearFind = CommonUtils.getCurrentDateFormat("yyyyy");
			
			if (Integer.parseInt(yearFind)<2500) {								
				yearFind = (""+(Integer.parseInt(yearFind)+543)).substring(2);			
			}else {
				yearFind = yearFind.substring(2);
			}			
		}
				
		request.getSession().setAttribute("monthFind", monthFind);
		request.getSession().setAttribute("yearFind", yearFind);
		
		String hql = "";
		if(itemFind==null||itemFind.trim().equals("")) {
			hql = "FROM BCDebitNote2   " +
					 " WHERE (docNo like 'dn%' ) " +
					 " ORDER BY docNo desc";			
		}else {
			hql = "FROM BCDebitNote2  " +
			 		 " WHERE (docNo like 'dn%'  ) " +
					 " and (docNo  like '%"+itemFind.trim()+"%' or "+					 
					 "      taxNo like '%"+itemFind.trim()+"%') "+	
					 " ORDER BY docNo desc";
		}
		System.out.println(hql);
		Page.setPage(request, hql);	
	}
	@SuppressWarnings("unchecked")
	public boolean add(ActionForm form, HttpServletRequest request,
			HttpServletResponse response) {
		
		BCDebitNote2  dn = (BCDebitNote2)BCDebitNote2BO.getObject(form);
		
		String user 	 = (String)request.getSession().getAttribute("userName");
		dn.setCreatorCode(user);
		dn.setCreateDateTime(new Date());
		
		new BCDebitNote2DAO().add(dn);
		
		// ถ้ามีเลขที่ใบกำกับภาษี (taxNo) ให้เพิ่มใน BCInputTax 		
		if(dn.getTaxNo()!=null && !dn.getTaxNo().equals("")) {
			BCInputTaxBean tax = (BCInputTaxBean)BCInputTaxBO.getObjectDN(form);
			tax.setCreatorCode(user);
			new BCInputTaxDAO().add(tax);
		}		
		
		BCAPDAO apDao = new BCAPDAO();
		apDao.updateDebtAmount(dn.getApCode(), dn.getSumOfTotalTax(), "DN");		
		System.out.println("update :DebtAmount"); 		
		
		ITTL_P2 p2 = (ITTL_P2)getDNForP2(dn);
		
		
		ArrayList unitList = (ArrayList)request.getSession().getAttribute("unitCodeList");
		for (int j = 0; j < unitList.size(); j++) {
			BCItemUnitBean uBean = (BCItemUnitBean)unitList.get(j);
			if(p2.getUnitName().equals(uBean.getCode())) {
				p2.setUnitName(uBean.getName());
				break;
			}						
		}		
		new BCDebitNote2DAO().add(p2);
		// ใส่ข้อมูล itemCode รายการนั้นใน table: processStock 
		ProcessStockDAO p = new ProcessStockDAO();
		String[] item_of_service = {"A-01", "A-02", "C-3",  "D-03", "D-04", "D-4",  "E-04", "E-05", "E-4",  "E-5",  "E-S-E",
									"F-04", "F-05", "F-06", "F-4",  "F-5",  "F-6",  "G-06", "G-08", "G-10", "G-11", "G-12", 
									"G-13", "G-14", "G-24", "GE",   "H-07", "H-08", "H-15", "HO",   "I-10", "I-16", "IM",
									"INT",  "J-11", "J-17", "K-14", "K-15", "K-16", "K-17", "K-18", "L-18", "L-19", "M-19",
									"M-21", "N-20", "N-22", "O-21", "P-22", "P-23", "Q-23", "R-24", "R-25", "S-25", "SE", "TREEX", "TRECO", 
									"SER-006","SES","ST",   "T-26", "U-27", "V-28", "Z-01", "Z-02", "Z-03", "Z-04", "Z-05", "Z-06"};
		
		Iterator it = dn.getBcDebitNoteSub2s().iterator();
		
		while(it.hasNext()) {
			BCDebitNoteSub2 sub = (BCDebitNoteSub2)it.next();
								
			boolean isItemService = false;
			for (int i = 0; i < item_of_service.length; i++) {
				if(item_of_service[i].contains(sub.getItemCode())) {
					isItemService = true;
				}				
			}
			if(isItemService==false) {
	        	ProcessStockBean bean = new ProcessStockBean();
	        	bean.setItemCode(sub.getItemCode());
	        	bean.setDocDate(sub.getDocDate());
	        	bean.setProcessFlag(0);
	        	bean.setFlowStatus(1);
	        	bean.setProcessType(7);		//สำหรับเพิ่มหนี้
	        	bean.setProcessCase(1);//  บันทึกเอกสารให้ =1, แก้ไขเอกสารให้=2,ลบเอกสารให้=3
	        		        	
	        	p.add(bean);
	        	
	    		System.out.println(CommonUtils.getDateTimeForStamp()+" #user:"+user+" #use :ProcessStockDAO #mode :add "+
	  				  "#item:"+sub.getItemCode());
// 				BCWinService จะ update: lastBuyPrice ให้กับ item ที่ซื้อเข้ามา แบบ auto อยู่แล้ว	
//	    		new BCItemDAO().updateLastBuyPrice(sub.getItemCode(),sub.getPrice());
			}
		}		
		request.setAttribute("docNoPrint", p2.getDocNo());
		return true;
	}
	
	@SuppressWarnings("unchecked")
	private ITTL_P2 getDNForP2(BCDebitNote2 dn) {
		ITTL_P2 p2 = new ITTL_P2();
		
		
		p2.setDocNo(dn.getDocNo());
		p2.setTaxNo(dn.getTaxNo());
		
		p2.setSumOfItemAmountOfPO(dn.getSumOfItemAmount());
		p2.setTaxAmountOfPO(dn.getSumOfTaxAmount());
		p2.setTotalAmountOfPO(dn.getSumOfTotalTax());
		
		p2.setSumOfItemAmountOfInvoice(dn.getSumOfItemAmount());
		p2.setTaxAmountOfInvoice(dn.getSumOfTaxAmount());
		p2.setTotalAmountOfInvoice(dn.getSumOfTotalTax());
		p2.setApCode(dn.getApCode());
		p2.setDocDate(dn.getDocDate());
		p2.setPoDate(dn.getDocDate());
		Iterator it = dn.getBcDebitNoteSub2s().iterator();
		while (it.hasNext()) {
			BCDebitNoteSub2 sub = (BCDebitNoteSub2) it.next();
			p2.setItemCode(sub.getItemCode());
			p2.setItemName(sub.getItemName());
			p2.setQty(sub.getDiscQty());
			p2.setPrice(sub.getPrice());
			p2.setDiscountWordLineItem(sub.getDiscountWord());
			p2.setDiscountAmountLineItem(sub.getDiscountAmount());
			p2.setAmount(sub.getAmount());
			
			p2.setUnitName(sub.getUnitCode());
			p2.setIttl_purchaseCode(sub.getInvoiceNo());
		}
		return p2;
	}
	
	@SuppressWarnings("unchecked")
	private static BCDebitNote2 getObject(ActionForm form) {
		
		BCDebitNote2Form sForm = (BCDebitNote2Form)form;
		
		BCDebitNote2 s = new BCDebitNote2();
		s.setDocNo(sForm.getDocNo());
		s.setTaxNo(sForm.getTaxNo());
		s.setDocDate(CommonUtils.convertStringToDate(sForm.getDocDate()));
		s.setCreditDay(sForm.getCreditDay());
		s.setDueDate(CommonUtils.convertStringToDate(sForm.getDueDate()));
		s.setTaxType(sForm.getTaxType());
		s.setApCode(sForm.getApCode());
		s.setDepartCode(sForm.getDepartCode());
		s.setTaxRate(7d);
		s.setIsConfirm(0);
		s.setMyDescription("data from iTTL");
		
		s.setSumOfItemAmount(sForm.getSumOfItemAmount());
		s.setSumOldAmount(sForm.getOldAmount());
		s.setSumTrueAmount(sForm.getSumTrueAmount());
		s.setSumofBeforeTax(sForm.getSumOfItemAmount());
		s.setSumOfTaxAmount(sForm.getSumOfTotalTax()-sForm.getSumOfItemAmount());
		s.setSumOfTotalTax(sForm.getSumOfTotalTax());
		
		s.setSumOfExceptTax(0d);
		s.setSumOfZeroTax(0d);
		s.setNetDebtAmount(sForm.getSumOfTotalTax());
		s.setSumExchangeProfit(0d);
		s.setBillBalance(sForm.getSumOfTotalTax());
		s.setCurrencyCode("BAHT");
		s.setExchangeRate(1d);
		s.setGlFormat("P06");
		s.setGlStartPosting(1);
		s.setIsPostGL(0);
		s.setIsCancel(0);
		s.setIsProcessOK(0);
		s.setIsCompleteSave(1);
		s.setGlTransData(0);
		
		s.setReturnStatus(0);
		s.setStatementState(0);
		
		s.setCauseType(sForm.getCauseType());
		s.setCauseCode(sForm.getCauseCode());
		s.setProjectCode(sForm.getProjectCode());
		s.setBillGroup(sForm.getBillGroup());
		
		s.setPayBillAmount(sForm.getSumOfTotalTax());
		s.setPrepayAmount(sForm.getSumOfTotalTax());
		
		
		HashSet hashSetInv = new HashSet();			
		
//		for(int i=0; i<sForm.getInvoiceNo2().length; i++ ) {
			BCInvDebitNote2 invDN = new BCInvDebitNote2();
			invDN.setDocDate(CommonUtils.convertStringToDate(sForm.getDocDate()));
			invDN.setApCode(sForm.getApCode());
			invDN.setDebitNoteNo(sForm.getDocNo());
			
			invDN.setReturnStatus(0);
			invDN.setInvoiceNo(sForm.getDocNoInv());
			
			invDN.setInvExchangeRate(1d);
			invDN.setNewExchangeRate(1d);
			invDN.setOldAmount(sForm.getOldAmount());
			invDN.setSumOfItemAmount(sForm.getSumOfItemAmount());
			invDN.setDiscountAmount(0d);
			invDN.setDiffAmount(sForm.getSumOfTotalTax());
			invDN.setZeroTaxAmount(0d);
			invDN.setExceptTaxAmount(0d);
			invDN.setTrueAmount(sForm.getSumTrueAmount());
			invDN.setHomeAmount1(sForm.getSumOfTotalTax());
			invDN.setHomeAmount2(sForm.getSumOfTotalTax());
			
			invDN.setExchangeProfit(sForm.getSumOfTotalTax());
			invDN.setIsCancel(0);
			
			invDN.setBcDebitNote2(s);
			hashSetInv.add(invDN);
//		}
		s.setBcInvDebitNote2s(hashSetInv);	
		
		HashSet hashSet = new HashSet();			
		
//		for(int i=0; i<sForm.getItemCode().length; i++ ) {
											
			BCDebitNoteSub2 sub = new BCDebitNoteSub2();
			sub.setMyType(3);
			sub.setTaxNo(s.getTaxNo());
			sub.setTaxType(s.getTaxType());
			sub.setItemCode(sForm.getItemCode());
			sub.setDocDate(s.getDocDate());
			sub.setApCode(s.getApCode());
			sub.setDepartCode(s.getDepartCode());
			sub.setWhCode("10");
			sub.setShelfCode("10");
			sub.setDiscQty(sForm.getDiscQty());
			sub.setTempQty(sForm.getDiscQty());
			sub.setBillQty(sForm.getBillQty());
			sub.setPrice(sForm.getPrice());
			
			if(CommonUtils.isNumberPercent(sForm.getDiscountAmount())) {
				sub.setDiscountWord(sForm.getDiscountAmount());
				double percent1 = Double.valueOf( sForm.getDiscountAmount().substring(0, sForm.getDiscountAmount().length()-1) );
				
				DecimalFormat f = new DecimalFormat("#.00");
				double subDiscountAmount = Double.valueOf( f.format(sub.getDiscQty()* sub.getPrice()*percent1/100));
				sub.setDiscountAmount(subDiscountAmount);
			}else {
				sub.setDiscountWord(sForm.getDiscountAmount()  );
				sub.setDiscountAmount(Double.valueOf(sForm.getDiscountAmount()  ));
			}
			sub.setAmount(sForm.getAmount());
			sub.setNetAmount(sForm.getAmount());
			sub.setHomeAmount(sForm.getAmount());
			sub.setUnitCode(sForm.getUnitCode());
			sub.setInvoiceNo(sForm.getDocNoInv2());
			sub.setProjectCode(s.getProjectCode());
			sub.setCurrencyCode("BAHT");
			sub.setExchangeRate(1d);
			sub.setTransState(0);
			sub.setIsCancel(0);
			sub.setStockProcess(0);
			sub.setLineNumber(1);
			
			sub.setSumOfCost(sub.getAmount());
			sub.setItemName(sForm.getItemName());
			sub.setCauseType(s.getCauseType());
			sub.setTaxRate(s.getTaxRate());
			sub.setIsProcess(1);
			
			sub.setBcDebitNote2(s);			
			hashSet.add(sub);
//		}
			
		s.setBcDebitNoteSub2s(hashSet);
		
		return s;
	}
	
	@SuppressWarnings("unchecked")
	public BCDebitNote2Form findDebitNote2(HttpServletRequest request) {
		
		BCDebitNote2Form dn = new BCDebitNote2Form();
		
		String docNo = (String)request.getParameter("docNo");
		
		List dnList = new BCStkRefundDAO().find("FROM BCDebitNote2 WHERE docNO = '"+docNo+"'");
		for (int i = 0; i < dnList.size(); i++) {
			BCDebitNote2 bean = (BCDebitNote2)dnList.get(i);
			
			dn.setDocNo(bean.getDocNo());
			dn.setTaxNo(bean.getTaxNo());		
			dn.setDocDate(CommonUtils.convertDateToString(bean.getDocDate()));									
			dn.setDueDate(CommonUtils.convertDateToString(bean.getDueDate()));
			dn.setTaxType(bean.getTaxType());										
			dn.setApCode(bean.getApCode());
			dn.setDepartCode(bean.getDepartCode());
			dn.setCauseType(bean.getCauseType());
			dn.setCauseCode(bean.getCauseCode());
			dn.setProjectCode(bean.getProjectCode());									
			dn.setBillGroup(bean.getBillGroup());
			dn.setTaxRate(bean.getTaxRate());																
			dn.setSumOldAmount(bean.getSumOldAmount());
			dn.setSumOfItemAmount(bean.getSumOfItemAmount());	
			dn.setSumofBeforeTax(bean.getSumofBeforeTax());
			dn.setSumOfTaxAmount(bean.getSumOfTaxAmount());
			dn.setSumOfTotalTax(bean.getSumOfTotalTax());
			dn.setSumOfExceptTax(bean.getSumOfExceptTax());
			dn.setSumTrueAmount(bean.getSumTrueAmount());
			dn.setMyDescription(bean.getMyDescription());
			dn.setCurrencyCode(bean.getCurrencyCode());
			dn.setExchangeRate(bean.getExchangeRate());
			
			dn.setCreditDay(bean.getCreditDay());
			
			dn.setTaxDate(CommonUtils.convertDateToString(bean.getDocDate()));
			Iterator itsub = bean.getBcDebitNoteSub2s().iterator();
			while (itsub.hasNext()) {
				BCDebitNoteSub2 dnSub = (BCDebitNoteSub2) itsub.next();
				
				dn.setItemCode(dnSub.getItemCode());
				dn.setItemName(dnSub.getItemName());
				dn.setDocNoInv(dnSub.getInvoiceNo());
				dn.setDocNoInv2(dnSub.getInvoiceNo());
				dn.setPrice(dnSub.getPrice());
				dn.setDiscQty(dnSub.getDiscQty());
				dn.setBillQty(dnSub.getBillQty());
				dn.setPrice(dnSub.getPrice());
				dn.setDiscountWord(dnSub.getDiscountWord());
				dn.setDiscountAmount(""+dnSub.getDiscountAmount());
				dn.setAmount(dnSub.getAmount());
				dn.setWhCode(dnSub.getWhCode());
				dn.setShelfCode(dnSub.getShelfCode());
				dn.setUnitCode(dnSub.getUnitCode());
				
			}
			
			Iterator itInvdn = bean.getBcInvDebitNote2s().iterator();			
			while (itInvdn.hasNext()) {
				BCInvDebitNote2 invdn = (BCInvDebitNote2)itInvdn.next();
				//System.out.println(invdn.getStkRefundNo() +"\t\t"+invdn.getOldAmount());
				//dn.setDocNoInv(invdn.getStkRefundNo());
				dn.setOldAmount(invdn.getOldAmount());
				
				
			}
			List apList = new BCDebitNote2DAO().find("FROM BCAPBean WHERE code = '"+bean.getApCode()+"'");
			if(apList!=null && apList.size()>0) {
				BCAPBean ap = (BCAPBean)apList.get(0);
				request.setAttribute("apName", ap.getName1());
			}
//			private	String	taxAmount;			
		}
		
		return dn;
	}
	public boolean delete(ActionForm form, HttpServletRequest request,
			HttpServletResponse response) {
		BCDebitNote2Form dn = (BCDebitNote2Form)form;		

		String user 	 = (String)request.getSession().getAttribute("userName");
		System.out.println(CommonUtils.getDateTimeForStamp()+" #user:"+user+" #use :BCDebitNote2DAO #mode :delete");		
		
		request.setAttribute("itemFind", dn.getDocNo());
		
		return new BCDebitNote2DAO().deleteDN(dn.getDocNo());
	}
}
